<?php
/**
 * This file is part of HelloWorld.
 *
 */
namespace common\models;

use common\helpers\CommonHelper;
use Yii;

/**
 * This is the model class for table "sys_app_push".
 *
 * @property string $id 主键
 * @property string $title 标题
 * @property string $content 内容
 * @property string $send_time 发送时间
 * @property int $push_type 0  全部 1 单个
 * @property string $user_range 用户范围  1 全部  2 单个手机号
 * @property string $create_time 添加时间
 * @property int $offline_time 离线保存 0 当前用户推送
 * @property int $is_read 是否已读 0 否 1 是
 * @property string $oper_user 操作人
 * @property string $link 跳转链接
 */
class AppPushModel extends BaseModel
{
    const RENT_STATUS_IDLE = 1;

    const RENT_STATUS_RENTING = 2;

    public $start_time;

    public $end_time;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%app_push}}';
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [
                ['user_range'],
                'string',
                'when' => function ($model, $attribute) {
                    return ! is_array($model->{$attribute});
                },
            ],
            [['content', 'title', 'send_time', 'start_time', 'end_time', 'oper_user'], 'string'],
            [['offline_time', 'push_type', 'is_read'], 'integer'],
            [['title', 'content', 'user_range'], 'required', 'on' => ['create']],
            [['create_time', 'send_time'], 'default', 'value' => date('Y-m-d H:i:s'), 'on' => ['create']],
            ['user_range', 'default', 'value' => '1', 'on' => ['create']],
            ['is_read', 'default', 'value' => 0, 'on' => ['create']],
            [['link'], 'string', 'max' => 200],
            [
                'oper_user',
                'filter',
                'filter' => function ($value) {
                    return $this->getCurrentOperateUser($value);
                },
                'when' => function ($model) {
                    return Yii::$app->components['user']['identityClass'];
                },
                'on' => ['create', 'update'],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'send_time' => '发送时间',
            'push_type' => '类型',
            'user_range' => '接收人',
            'create_time' => '添加时间',
            'offline_time' => '离线保存',
            'is_read' => '是否已读',
            'oper_user' => '操作人',
            'start_time' => '开始时间',
            'end_time' => '截止时间',
            'link' => '跳转链接',
        ];
    }

    /**
     * 搜索.
     * @param int $page
     * @param int $limit
     * @param string $orderBy
     * @param mixed $select
     * @param mixed $groupBy
     * @return array
     */
    public function search(array $params = [], $select = '*', $groupBy = '')
    {
        $this->setAttributes($params);
        if (! $this->validate()) {
            return CommonHelper::toResult(-1, implode(';', $this->getFirstErrors()));
        }
        $query = static::find();
        $query->andFilterWhere(['like', 'title', $this->title]);
        $query->andFilterWhere(['=', 'oper_user', $this->oper_user]);
        if ($this->user_range == '全部') {
            $query->andFilterWhere(['=', 'push_type', 0]);
        } elseif (is_array($this->user_range)) {
            $query->andFilterWhere(['in', 'user_range', $this->user_range]);
        } elseif ($this->user_range) {
            $query->andFilterWhere(['=', 'push_type', 1]);
            $query->andFilterWhere(['like', 'user_range', $this->user_range]);
        }
        $query->andFilterWhere(['>=', 'send_time', $this->start_time]);
        $query->andFilterWhere(['<=', 'send_time', $this->end_time]);
        if (!empty($params['end_create_time'])) {
            $query->andFilterWhere(['>=', 'create_time', $params['end_create_time']]);
        }

        // 分页
        if (! empty($params['limit'])) {
            // 分页返回统计
            $result['count'] = $query->count();

            $query->offset(isset($params['offset']) ? $params['offset'] : ($params['page'] - 1) * $params['limit']);
            $query->limit($params['limit']);
        }

        if ($groupBy) {
            $query->groupBy($groupBy);
        } else {
            // 排序
            if (! empty($params['_sort_field'])) {
                $query->orderBy($params['_sort_field'] . ' ' . $params['_sort_type']);
            } else {
                $query->orderBy('create_time desc');
            }
        }

        $result['data'] = $query->select($select)->asArray()->all();

        return CommonHelper::toResult($result);
    }

    /**
     * 获取客户端ID.
     * @param $mobile
     */
    /*public static function getClientId($mobile)
    {
        return Yii::$app->redis->get('apply_member_clientid:' . $mobile);
    }*/
    public static function getClientId($mobile)
    {
        $user = Yii::$app->dstOssGatewayApi->getUserCenterInfoByMobile($mobile)['data'];
        if (!$user) {
            return '';
        }
        $member = MemberModel::getEffectiveOne(['member_id' => $user['id']], 'clientid');
        return $member ? $member->clientid : '';
    }

    /**
     * 日志.
     */
    public function log(array $data = [])
    {
        if (empty($data)) {
            return $data;
        }
        if (isset(Yii::$app->controller->id) && Yii::$app->controller->id != 'app-push') {
            return [];
        }
        isset($data['push_type']) && $data['push_type'] = Yii::$app->params['appPushType'][$data['push_type']];
        if (isset($data['user_range']) && $data['user_range'] == '1') {
            $data['user_range'] = '全部';
        }
        isset($data['is_read']) && $data['is_read'] = Yii::$app->params['yesNo'][$data['is_read']];
        if (isset($data['offline_time'])) {
            $data['offline_time'] = $data['offline_time'] ? '不保持' : '保持' . $data['offline_time'] . '小时';
        }

        return $data;
    }
}
